import React, { Component } from 'react';
import { connect } from 'dva';
import { Card, Modal, Button, message, Typography, Table } from 'antd';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import Separate from '@/components/Separate';
import styles from '@/components/common/PateoTable/TableList.less';
import router from 'umi/router';
import { routerRedux } from 'dva/router';
import textVar from '../textVar';
import Ellipsis from '@/components/Ellipsis';

const mapStateToProps = (state: any) => {
  return {
    listData: state?.commodityManagement?.pageData,
    loading: state.loading.effects['commodityManagement/postFetchPage'],
    permissions: state?.menu?.permissions,
  };
};

class index extends Component {
  state = {
    rightQuery: {},
    brand: [],
    series: [],
  };
  payloadUrl = '/optshop/m18/goods/queryGoodsList';
  payloadType = 'commodityManagement/postFetchPage';
  searchRef = null;

  componentDidMount() {
    this.getList();
    // this.setBrand();
  }

  getList = () => {
    // 获取数据
    const { rightQuery } = this.state;
    this.postAxios(rightQuery);
  };
  postAxios = (rightQuery: any) => {
    const { dispatch } = this.props;
    const { pageSize, current } = rightQuery;
    const page = current ? { page: { pageSize, current } } : {};

    dispatch({
      type: this.payloadType,
      payload: { url: this.payloadUrl, ...rightQuery, ...page },
      callback: (res: any) => {
        const { statusCode, data } = res || {};
        if (statusCode === '0') {
          this.setState(data);
        }
      },
    });
  };
  // 重置品牌
  setBrand = () => {
    this.searchRef.resetFields(['brandId', 'carSeries']);
    this.props.dispatch({
      type: 'commodityManagement/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        const { statusCode, data } = res;
        if (statusCode === '0') {
          this.setState({
            brand: data.map(e => ({
              label: e.brandName,
              value: e.brandCode,
            })),
          });
        }
      },
    });
  };
  //   // 重置车系
  //   setSeries = () => {
  //     // 重置
  //     this.searchRef.resetFields(['carSeries']);
  //     this.setState({ series: [] });
  //     // 获取属性
  //     const brandId = this.searchRef.getFieldValue('brandId');
  //     brandId &&
  //       this.props.dispatch({
  //         type: 'vehicleInfoQuery/getDataWithRes',
  //         payload: {
  //           url: '/common/vehicle/getserieslist',
  //           brandId,
  //         },
  //         callback: e => {
  //           const { statusCode, data } = e;
  //           if (statusCode === '0') {
  //             this.setState({
  //               series: data.map(e => ({
  //                 label: e.name,
  //                 value: e.code,
  //               })),
  //             });
  //           }
  //         },
  //       });
  //   };
  render() {
    const { rightQuery, brand, series } = this.state;
    const {
      loading,
      location: { pathname = '/' },
      listData: { m18GoodsList, pagination, goodsGatherVo },
    } = this.props;
    const searchItems = [
      //   {
      //     type: 'select',
      //     title: `品牌`,
      //     key: 'brandId',
      //     selectOptions: brand,
      //     onChange: () => {
      //       this.setSeries();
      //     },
      //   },
      //   {
      //     type: 'select',
      //     title: `车系`,
      //     key: 'carSeries',
      //     selectOptions: series,
      //   },
      {
        type: 'select',
        title: `商品分类`,
        key: 'goodsTypeId',
        selectOptions: textVar.goodsType,
        keyValue:['key',"value"]
      },
      {
        type: 'select',
        title: `商品状态`,
        key: 'saleStatus',
        selectOptions: textVar.goodsStatus,
        keyValue:['key',"value"]
      },
      {
        type: 'input',
        title: `商品名称`,
        key: 'productName',
        maxLength: 20,
      },
    ];

    const rightColumns = [
      //   {
      //     title: `品牌`,
      //     dataIndex: 'brandName',
      //   },
      //   {
      //     title: `车系`,
      //     dataIndex: 'carSeries',
      //   },
      {
        title: `商品名称`,
        dataIndex: 'productName',
      },
      {
        title: `商品sku名称`,
        dataIndex: 'skuList',
        render:(txt=[])=>{
            return txt.map((e,i)=>{
                return <p style={{marginBottom:"0",paddingTop:i>0?"15px":"0"}}>{e?.skuName}</p>
            })
        }
      },
      {
        title: `商品现价`,
        dataIndex: 'skuList',
        render:(txt=[])=>{
            return txt.map((e,i)=>{
                return <p style={{marginBottom:"0",paddingTop:i>0?"15px":"0"}}>{e?.finalPrice}</p>
            })
        }
      },
      //   {
      //     title: `商品价格`,
      //     dataIndex: 'originPrice',
      //   },
      //   {
      //     title: `商品折扣价`,
      //     dataIndex: 'configLevelName',
      //   },
      {
        title: `商品分类`,
        dataIndex: 'goodsTypeId',
      },
      {
        title: `商品描述`,
        dataIndex: 'description',
        render: (text: string) => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: `是否热门`,
        dataIndex: 'isHot',
        render: (txt: number) => {
          return txt == 1 ? '是' : '否';
        },
      },
      {
        title: `有效日期`,
        dataIndex: 'validDate',
      },
      {
        title: `商品状态`,
        dataIndex: 'saleStatus',
        render: (text: number) => textVar.goodsStatus.find(e => e.key === text)?.value || '',
      },
      {
        title: `商品总量（最大购买量）`,
        dataIndex: 'maxOrderNum',
      },
      {
        title: `操作`,
        dataIndex: '操作',
        fixed: 'right',
        width: 100,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              auth: 'commodityManagement_info',
              onConfirm: () => {
                const { dispatch } = this.props;
                dispatch(
                  routerRedux.push({
                    pathname: '/commodity/commodityManagement/commodityManagementDetail',
                    record,
                  }),
                );
                // router.push(`/commodity/commodityManagement/commodityManagementDetail?id=`);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => <span>共&nbsp;{!pagination ? 0 : pagination.total}&nbsp;条</span>,
    };

    const rightTable = {
      columns: rightColumns,
      dataSource: [...(m18GoodsList || [])],
      loading,
      rowKey: (record: any) => `${record.productId}-${record.validDate}${new Date().getTime()}`,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const { goodsSpus, goodsSkus, goodsAllSkus } = goodsGatherVo || {};
    const separateList = [
      {
        title: goodsSpus || 0,
        text: '在售SPU',
      },
      {
        title: goodsSkus || 0,
        text: '在售SKU',
      },
      {
        title: goodsAllSkus || 0,
        text: '商家SKU',
      },
    ];
    return (
      <div>
        <Card>
          <Separate list={separateList}></Separate>
        </Card>
        <Card className={styles.standardTable}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: this.payloadType, url: this.payloadUrl }}
            saveFormValues={(val: any) => this.setState({ rightQuery: { ...rightQuery, ...val } })}
            handleFormReset={() => this.setState({ rightQuery: {}, series: [] })}
            dispatchFn={this.postAxios}
            onRef={e => {
              this.searchRef = e.current;
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            tableProps={rightTable}
            fetchParams={{ type: this.payloadType, url: this.payloadUrl }}
            formValues={rightQuery}
            dispatchFn={this.postAxios}
          />
        </Card>
      </div>
    );
  }
}

export default connect(mapStateToProps)(index);
